const appInstance = getApp();
import request from '../../utils/request'
// import PubSub from 'pubsub-js';


Page({

  /**
   * 页面的初始数据
   */
  data: {
    bannerList: [], // 轮播图数据
    recommendList: [], // 推荐歌单
    topList: [], // 排行榜数据
    userInfo: {},
    index: 0,
    palyshow: true,
    id: '',
    arname: '',
    musicLink: '',
    picurl: '',
    songname: '',
    type: '',
    isplaying: false,
    icon_play: false,
    cardCur: 0,
    listid:'',
    topListitem:[],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let that = this;
    appInstance.globalData.backgroundAudioManager = wx.getBackgroundAudioManager();
    appInstance.globalData.backgroundAudioManager.onPlay(() => {
      console.log("播放")
    })
    let bannerListData = await request('/banner', { type: 2 });
    this.setData({
      bannerList: bannerListData.banners
    })

    // 获取推荐歌单数据
    let recommendListData = await request('/personalized', { limit: 10 });
    this.setData({
      recommendList: recommendListData.result
    })

    // 获取排行榜数据
    /*
    * 需求分析：
    *   1. 需要根据idx的值获取对应的数据
    *   2. idx的取值范围是0-20， 我们需要0-4
    *   3. 需要发送5次请求
    * 前++ 和 后++的区别
    *   1. 先看到是运算符还是值
    *   2. 如果先看到的是运算符就先运算再赋值
    *   3. 如果先看到的值那么就先赋值再运算
    * */

    let index = 0;
    let resultArr = [];
    
      let topListData = await request('/toplist/detail');
      let list = topListData.list.slice(0, 4)
      // console.log(list)
      // splice(会修改原数组，可以对指定的数组进行增删改) slice(不会修改原数组)
      // let topListItem = { name: topListData.list.name, tracks: topListData.list.tracks.slice(0, 3) };
      resultArr=list
      
      //获取歌单详情
      this.getlistDetail(list)

      // 不需要等待五次请求全部结束才更新，用户体验较好，但是渲染次数会多一些
      this.setData({
        topList: resultArr
      })
    



    // 更新topList的状态值, 放在此处更新会导致发送请求的过程中页面长时间白屏，用户体验差
    // this.setData({
    //   topList: resultArr
    // })



    getApp().watch(that.watchBack)
    getApp().watchplay(that.watchplay)

  },





  //监听全局音乐变量
  watchBack: function (value) {
    // console.log(value)
    this.setData({
      isplaying: true
    })
    // console.log(appInstance.globalData.isMusicPlay)
    this.bofang()

  },

  //跳到音乐界面
  toSongDetail(event){
    wx.navigateTo({
      url: `/pages/songPackage/pages/playmusic/playmusic?type=${this.data.type}&musicId=` + this.data.id
    })
  },


  watchplay: function (value) {
    this.setData({
      icon_play: value
    })
  },

  // 跳转至recommendSong页面的回调
  toRecommendSong() {
    wx.navigateTo({
      url: '/pages/songPackage/pages/recommendSong/recommendSong'
    })
  },


  // 跳转至other页面
  toOther() {
    wx.navigateTo({
      url: '/songPackage/pages/other/other'
    })
  },

  handlegetUserInfo(res) {
    // console.log(res)
    if (res.detail.userInfo) {

      this.setData({
        userInfo: res.detail.userInfo
      })
      // console.log('用户信息:', this.data.userInfo)

    }
  },
  dianji() {
    // console.log(appInstance.globalData)
    if (!appInstance.globalData.isMusicPlay) { // 音乐播放
      appInstance.globalData.backgroundAudioManager.play();
      // appInstance.globalData.isMusicPlay = !appInstance.globalData.isMusicPlay
      this.setData({
        icon_play: appInstance.globalData.isMusicPlay
      })
    } else { // 暂停音乐
      appInstance.globalData.backgroundAudioManager.pause();
      // appInstance.globalData.isMusicPlay = !appInstance.globalData.isMusicPlay
      this.setData({
        icon_play: appInstance.globalData.isMusicPlay
      })
    }
  },

  bofang() {
    let that = this
    //  console.log("播放")
    let musicInfo = JSON.parse(wx.getStorageSync('songInfo'));
    let { id, arname, picurl, musicLink, songname, type } = appInstance.globalData.songInfo;
    this.setData({
      id,
      arname,
      picurl,
      musicLink,
      songname,
      type,
      icon_play: appInstance.globalData.isMusicPlay

    })
  },
  gotolists(event){
     let {listid} = this.data
    //  console.log(event.currentTarget.dataset.song.id)
    listid = event.currentTarget.dataset.song.id
    wx.navigateTo({
      url: '/pages/songPackage/pages/playListDetail/playListDetail?listid='+listid
    })
  },

  //前往歌单
  toplaylist(){
        wx.navigateTo({
      url: '/pages/songPackage/pages/playlist/playlist' 
    })
  },

  totopListDetail(event){
    console.log(event.currentTarget)
    let listid = event.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/songPackage/pages/topListDetail/topListDetail?listid='+listid
    })
},

 tomvList(){
  wx.navigateTo({
    url: '/pages/songPackage/pages/mvList/mvList' 
  })
 },
  // toSongDetail(event){
  //   // console.log(event.currentTarget.dataset)
  //   let {song, index} = event.currentTarget.dataset;
  //   console.log(event.currentTarget)
  //   this.setData({
  //     index
  //   })
  //   // 路由跳转传参： query参数
  //   wx.navigateTo({
  //     // 不能直接将song对象作为参数传递，长度过长，会被自动截取掉
  //     // url: '/pages/songDetail/songDetail?songPackage=' + JSON.stringify(songPackage)
  //     url: '/pages/songPackage/pages/songDetail/songDetail?musicId=' + song.id
  //   })
  // },



  cardSwiper(e) {
    this.setData({
      cardCur: e.detail.current
    })
  },

   async getlistDetail(list){
     let {topListitem} = this.data
        // list.forEach((item,index) => {
        //   let res = await request('/playlist/detail',{id:item.id})
        //   console.log(item.id)
        // })
        let idlist = []
        let res = []
        for(let index = 0;index<=list.length-1;index++){
          // console.log(list[index].id)
          res[index] = await request('/playlist/detail',{id:list[index].id})
          
        }

        // console.log(res)
        res.forEach((item,i)=>{
          let items = item.privileges.slice(0, 3)
          // console.log(items)
          let somid = []
          items.forEach((items,index)=>{
            somid.push(items.id)
          })
          idlist.push(somid)
        })
        // console.log(idlist)
        
        for(let i = 0;i<=idlist.length-1;i++){
          // console.log(list[index].id)
          let id = idlist[i].toString()
         
          res[i] = await request('/song/detail',{ids:id})
          topListitem.push(res[i])
          this.setData({
            topListitem
          })
        }

    },
   

    totopList(){
      wx.navigateTo({
        url: '/pages/songPackage/pages/topList/topList' 
      })
    },

    tosonger(){
      wx.navigateTo({
        url: '/pages/songPackage/pages/songer/songer' 
      })
    },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

